<template>
<div id="home">
  <div class="center">
    <div class="title">
      <span >我的虚拟机</span>
      <span @click="newOne">+ 新建虚拟机</span>
    </div>
     <!-- 没有数据的页面 -->
    <div class="noneDate" v-if="tableData.length == 0 && isRequire">
      <div class="noneimg"><img :src="img" alt=""></div>
      <div class="tip">老铁，暂时没有可用虚拟机哦！赶紧去<span @click="newOne">创建一台</span>吧！</div>
    </div>
    <!-- 虚拟机页面 -->
    <div class="tableBox" v-else>
      <!-- 表格 -->
      <div class="table">
        <template>
          <el-table :data="tableData" stripe style="width: 100%" border :header-cell-style="{background:'#f0f0f0'}">>
            <el-table-column label="图标"  align='center'>
              <template slot-scope="scope">
                <img :src="scope.row.image.image.real_cover" alt="" style="width: 30px;">
              </template>
            </el-table-column>
            <el-table-column prop="name" label="虚拟机名称" min-width= '140' align='center'>
              <template slot-scope="scope">
                <el-input v-if="scope.$index == activeIndex" v-model="scope.row.name" placeholder="修改名字" size="mini"></el-input>
                <span v-else>{{scope.row.name}}</span>
                <i class="iconfont icon-wancheng3" @click="complete(scope.$index, scope.row)" v-if="scope.$index == activeIndex"></i>
                <i class="iconfont icon-xiugai" @click="changeName(scope.$index, scope.row)" v-else></i>
              </template>
            </el-table-column>
            <el-table-column prop="image.image.name" label="镜像" min-width= '120' align='center' >
            </el-table-column>
            <el-table-column  label="配置"  min-width="210" align='center'>
              <template slot-scope="scope">
                <span class="peizhi">CPU:<span class="peizhiCon">{{scope.row.image.image.pre_vcpu}}核</span></span>
                <span class="peizhi">内存:<span class="peizhiCon">{{scope.row.image.image.pre_ram}}MB</span></span>
                <span class="peizhi">硬盘:<span class="peizhiCon">{{scope.row.image.image.pre_disk}}G</span></span>
              </template>
            </el-table-column>
            <el-table-column label="状态" min-width= "130" align='center'>
              <template slot-scope="scope">
                <span class="circle pdl" v-if="scope.row.status == '2'"></span>
                <span class="circle pdl close" v-else-if="scope.row.status == '3'"></span>
                <span class="circle pdl create" v-else-if="scope.row.status == '0'|| scope.row.status == '1'" style="position: absolute; left: 49px; top: 24px;"></span>
                <span class="circle pdl close" v-else></span>
                <span class="colorStatus" v-if="scope.row.status == '0'|| scope.row.status=='1'" style="position: absolute; left: 69px; top: 19px;">{{createing}}</span>
                <span class="colorStatus" v-else>{{scope.row.status | filStatus}}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作"  min-width="280" align='center'>
              <template slot-scope="scope">
                <!-- <el-button  type="success" size="mini" :disabled="scope.row.status == '0' || scope.row.status == '1' " @click="openwindow">{{btnOpen}}</el-button> -->

                <el-button  type="success" size="mini"   v-if="scope.row.status == '2'" @click="dakai(scope.$index, scope.row)">打开</el-button>
                <el-button  type="success" size="mini"  @click="openwindow(scope.$index, scope.row)" v-else :disabled="scope.row.status == '0' || scope.row.status == '1' ">开机</el-button>
                <el-button type="info" size="mini" :disabled="scope.row.status == '3' || scope.row.status == '0' || scope.row.status == '1'" @click="guanji(scope.$index, scope.row)">关机</el-button>
                <el-button type="danger" size="mini" :disabled="scope.row.status == '0'|| scope.row.status == '1' " @click="del(scope.$index, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </div>
      <!-- 表格的分页 -->
      <div class="page">
        <el-pagination background layout="prev, pager, next" :total="total" :page-size="7" @current-change="handleCurrentChange"></el-pagination>
      </div>
    </div>
  </div>
  <!-- dialog弹窗m没有u币 -->
  <el-dialog title="操作提示" :visible.sync="noneUb" width="482px"  class="noneUb">
    <div class="noneIco"> <i class="el-icon-warning"></i></div>
    <p class="text">Ｕ币不足，在任务中心完成任务<br>可以获得大量的U币奖励</p>
    <span slot="footer" class="dialog-footer">
      <el-button @click="gorenwu" type="success" size='small'>去做任务</el-button>
      <el-button @click="noneUb = false" size='small'>留在本页</el-button>
    </span>
  </el-dialog>
  <!-- dialog弹窗创建虚拟机 -->
  <el-dialog title="创建虚拟机" :visible.sync="virtual" width="652px"  class="virtual">
  <el-form :model="form">
    <el-form-item label="虚拟机名称:" >
      <!-- <el-input v-model="form.name" auto-complete="off"></el-input> -->
      <el-input v-model="input" placeholder="请输入虚拟机名称" size="medium"></el-input>
    </el-form-item>
    <el-form-item label="选择操作系统:" >
      <div class="block">
        <el-cascader :options="options" v-model="selectedOptions" size="medium">
      </el-cascader>
  </div>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button  size='small' type="success" @click="sureCreate">确 定</el-button>
    <el-button @click="virtual = false" size='small'>取 消</el-button>
  </div>
</el-dialog>
</div>
</template>

<script>
export default {
  name: 'home',
  data () {
    return {
      img: require('../assets/images/none.png'),
      options: [],
      selectedOptions: [],
      tableData: [],
      createing: '创建中',
      // 当前的索引
      activeIndex: null,
      // 是否请求过数据
      isRequire: false,
      // dialog没有u币
      noneUb: false,
      // dialog创建虚拟机
      virtual: false,
      // 创建的数据
      form: {},
      input: '',
      // 判断是否可以创建虚拟机
      chuangjian: false,
      total: null,
      page: 1,
      // 开机提示
      kaiTip: true,
      // 关机提示
      guanTip: true,
      time: null
    };
  },
  created () {
    // 判断本地的不再提示的状态有没有值，有值就不再提示；
    if (localStorage.kaiji) {
      this.kaiTip = false;
    }
    if (localStorage.guanji) {
      this.guanTip = false;
    }
  },
  mounted () {
    // 创建建中动画
    setInterval(() => {
      this.createing = this.createing + '.';
      if (this.createing === '创建中....') {
        this.createing = '创建中';
      }
    }, 1024);
    // 获取镜像
    this.getdata();
    this.getshili();
    // 获取状态
    // this.getStatus();
    // 如果有则循环操作状态
    if (sessionStorage.newjiqi) {
      setInterval(this.getshili, 20480);
    };
    // 以后不再提示的弹窗触发事件
    this.$bus.$on('dataStatus', config => {
      if (config.kaiji === '1') {
        this.kaiTip = false;
      } else if (config.kaiji === '0') {
        this.kaiTip = true;
      }
      if (config.guanji === '1') {
        this.guanTip = false;
      } else if (config.guanji === '0') {
        this.guanTip = true;
      }
    });
  },
  beforeDestroy: function () {
    this.$bus.$emit('comAlert');
  },
  methods: {
    getCookie (name) {
      let arr = document.cookie.match(new RegExp('(^| )' + name + '=([^;]*)(;|$)'));
      if (arr != null) {
        return unescape(arr[2]);
      } else {
        return null;
      }
    },
    // 获取实例列表
    getshili () {
      this.axios.get('compute/instance', {
        params: {
          page: this.page
        }
      })
        .then(({data}) => {
          if (data.code === 200) {
            this.tableData = data.data.data;
            this.total = data.data.total;
            this.isRequire = true;
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    gorenwu () {
      window.open('/niaowo');
    },
    // 获取镜像列表
    getdata () {
      this.axios.get('compute/image')
        .then(({data}) => {
          if (data.code === 200) {
            // this.options = data.data;
            let arr = data.data;
            // console.log(arr);
            for (let i = 0; i < arr.length; i++) {
              arr[i].value = arr[i].name;
              arr[i].label = arr[i].name;
              arr[i].children = arr[i].images;
              for (let j = 0; j < arr[i].children.length; j++) {
                arr[i].children[j].value = arr[i].children[j].image_id;
                arr[i].children[j].label = arr[i].children[j].name;
              }
            }
            this.options = arr;
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    // 获取状态信息
    getStatus () {
      this.axios.get('compute/instance/status-list')
        .then(({data}) => {
          if (data.code === 200) {
            this.status = data.data;
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    // 判断是否可以创建虚拟机
    isCreate () {
      this.axios.get('compute/instance/canApply')
        .then(({data}) => {
          if (data.code === 200) {
            this.chuangjian = true;
            if (this.chuangjian) {
              this.virtual = true;
            }
          } else {
            this.noneUb = true;
            this.$message({
              message: data.msg,
              type: 'warning'
            });
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    // 修改名字
    changeName (index, row) {
      this.activeIndex = index;
    },
    // 完成名字修改
    complete (index, row) {
      this.axios.post('compute/instance/rename', {
        name: row.name,
        instance_id: row.id
      })
        .then(({data}) => {
          if (data.code === 200) {
            this.activeIndex = null;
          } else {
            this.$message({
              message: data.msg,
              type: 'warning'
            });
          }
        });
    },
    // 打开
    dakai (index, item) {
      this.axios.get('compute/instance/console', {
        params: {
          instance_id: item.id
        }
      })
        .then(({data}) => {
          if (data.code === 200) {
            window.open(data.data.url, `console${item.id}`, {height: '100%', location: 'no', 'status': 'no'});
          } else {
            this.$message({
              message: data.msg,
              type: 'warning'
            });
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    // 开机接口
    postOn (item) {
      this.axios.post('compute/instance/on', {
        instance_id: item.id
      })
        .then(({data}) => {
          if (data.code === 200) {
            item.status = 2;
          } else {
            this.$message({
              message: data.msg,
              type: 'warning'
            });
          }
        });
    },
    // 开机打开新窗口
    openwindow (index, item) {
      if (this.kaiTip) {
        this.$bus.$emit('comAlert', {
          title: '确定要开机吗？',
          info: '开机将立即扣除一个U币，每隔10分钟会扣除一个U币。',
          infoHtml: '<div class="openHtml"><p><i class="el-icon-warning"></i>Linux &nbsp;&nbsp;&nbsp;系统默认用户名：root  &nbsp;&nbsp;&nbsp; 密码：123456</p><p><i class="el-icon-warning"></i>Ubuntu &nbsp;&nbsp;&nbsp;系统默认用户名：yun  &nbsp;&nbsp;&nbsp; 密码：123456</p></div>',
          kai: 1,
          button: [
            {
              text: '确定',
              callback: () => {
                this.postOn(item);
              }
            },
            {
              text: '取消',
              callback: () => {
              }
            }
          ]
        });
      } else {
        this.postOn(item);
      }
    },
    // 关机接口
    postOff (item) {
      this.axios.post('compute/instance/off', {
        instance_id: item.id
      })
        .then(({data}) => {
          if (data.code === 200) {
            item.status = 3;
          } else {
            this.$message({
              message: data.msg,
              type: 'warning'
            });
          }
        });
    },
    // 关机操作
    guanji (index, item) {
      if (this.guanTip) {
        this.$bus.$emit('comAlert', {
          title: '确定要关机吗？',
          info: '关机将立即扣除一个U币，每隔30分钟会扣除一个',
          kai: 2,
          iconTip: false,
          button: [
            {
              text: '确定',
              callback: () => {
                this.postOff(item);
              }
            },
            {
              text: '取消',
              callback: () => {
              }
            }
          ]
        });
      } else {
        this.postOff(item);
      }
    },
    // 删除接口调用
    postDel (index, item) {
      this.axios.post('compute/instance/delete', {
        instance_id: item.id
      })
        .then(({data}) => {
          if (data.code === 200) {
            this.tableData.splice(index, 1);
            if (this.tableData.length === 0 && this.page > 1) {
              this.isRequire = false;
              this.page = this.page - 1;
              this.getshili();
            }
            this.$message({
              message: '删除成功',
              type: 'success'
            });
          } else {
            this.$message({
              message: data.msg,
              type: 'warning'
            });
          }
        });
    },
    del (index, item) {
      this.$bus.$emit('comAlert', {
        title: '确定要删除吗？',
        info: '虚拟机删除后不可恢复，请注意保存数据!',
        button: [
          {
            text: '确定',
            callback: () => {
              this.postDel(index, item);
            }
          },
          {
            text: '取消',
            callback: () => {
            }
          }
        ]
      });
    },
    handleCurrentChange (val) {
      this.page = val;
      this.getshili();
    },
    // 判断有没有创建中的数据
    // newcreat () {
    //   let createStatus = this.tableData.some((item, index) => {
    //     return item.status === 0 || item.status === 1;
    //   });
    //   if (createStatus) {
    //     this.page = 1;
    //     this.time = setInterval(this.getshili, 10240);
    //   } else {
    //     clearInterval(this.time);
    //   }
    // },
    // 新建虚拟机
    newOne () {
      this.isCreate();
    },
    // 确定创建虚拟机
    sureCreate () {
      this.axios.post('compute/instance', {image_id: this.selectedOptions[1], name: this.input})
        .then(({data}) => {
          if (data.code === 200) {
            this.virtual = false;
            // 为了刷新页面不丢失定时器的执行
            this.page = 1;
            this.getshili();
            sessionStorage.setItem('newjiqi', '1');
            setInterval(this.getshili, 20480);
            this.$message({
              message: '创建虚拟机大约需要几分钟，请耐心等待！',
              type: 'warning'
            });
          } else {
            this.virtual = false;
            this.$message({
              message: data.msg,
              type: 'warning'
            });
          }
        });
    }
  },
  filters: {
    filStatus: function (value) {
      if (!value) {
        return false;
      }
      if (typeof (value) !== 'string') {
        value = value.toString();
      }
      // console.log(value);
      return {
        '0': '创建中',
        '1': '创建中',
        '2': '运行中',
        '3': '已关机',
        '4': '已删除',
        '5': '修改密码中',
        '125': '创建失败'
      }[value];
    }
  }
};
</script>

<style lang="scss">
#home {
  min-width: 1200px;
  .center {
    width: 1200px;
    margin: 0 auto;
  }
  @keyframes buling {
    from {
      background: #ff571d;
    }
    to {
      background: yellow;
    }
  }
  .title {
    position: relative;
    z-index: 999;
    height: 80px;
    display: flex;
    box-sizing: border-box;
    padding-bottom: 11px;
    justify-content: space-between;
    align-items: flex-end;
    border-bottom: 1px solid #dfdfdf;
    span:first-child {
      font-size: 18px;
      display: inline-block;
      height: 20px;
      width: auto;
      color: rgba(51, 51, 51, 1);
      padding-left: 20px;
      position: relative;
      &::before {
        position: absolute;
        content: "";
        width: 7px;
        height: 20px;
        background: rgba(16, 165, 125, 1);
        left: 0;
        top: 0;
      }
    }
    span:last-child {
      display: inline-block;
      width: 124px;
      height: 32px;
      background: rgba(16, 165, 125, 1);
      border-radius: 2px;
      line-height: 32px;
      text-align: center;
      font-size: 14px;
      color: rgba(255, 255, 255, 1);
      cursor: pointer;
    }
  }
  .table {
    margin-top: 24px;
    .circle {
      display: inline-block;
      width: 12px;
      height: 12px;
      border-radius: 50%;
      margin-right: 4px;
      background: #13b203;
      &.close {
        background: #999999;
      }
      &.create {
        background: #ff571d;
        animation: buling 1s infinite steps(2);
      }
    }
    .iconfont {
      margin-left: 10px;
      font-size: 16px;
      cursor: pointer;
    }
    .el-input {
      width: 110px;
    }
    .peizhi {
      color: #9e9e9e;
      margin-right: 10px;
      .peizhiCon {
        color:#606266;

      }
    }
    .pdl {
      // margin-left: 36px;
    }
  }
  .page {
    margin-top: 38px;
    margin-bottom: 50px;
    text-align: center;
    .el-pagination.is-background .el-pager li:not(.disabled).active {
      background: #10a57d;

    }
  }
  .noneDate {
    margin-top: 230px;
    .noneimg {
      text-align: center;
      img {
        width: 194px;
        height: 140px;
      }
    }
    .tip {
      margin-top: 73px;
      font-size: 18px;
      font-family: MicrosoftYaHei;
      font-weight: 400;
      color: rgba(129, 129, 129, 1);
      text-align: center;
      span {
        color: #FA520A;
        cursor: pointer;
      }
    }
  }
  // 没有u币弹窗
  .noneUb {
    margin-top: 22vh;
    .noneIco {
      text-align: center;
      i {
        color: #f2bd07;
        font-size: 40px;
      }
    }
    .text {
      word-wrap: break-word;
      word-break: normal;
      text-align: center;
      font-size:18px;
      font-family:MicrosoftYaHei;
      font-weight:400;
      color:rgba(51,51,51,1);
      margin-top: 10px;
    }
  }
  // 创建虚拟机弹窗
  .virtual {
    .el-input {
      width: auto;
    }
  }
  .el-dialog__wrapper {
    margin-top: 20vh;
  }
}
</style>
